{include file="$header" /}
<div class="mk-app-warp">
    <mk-table-header
        :add-url="addUrl"
        :del-url="delUrl"
        :rows="rows"
        @del="del()"
        @add="openDrawer()"
        @expand-all="expandAll($event)"
        expand>
    </mk-table-header>
    <el-table
        ref="table"
        row-key="id"
        v-loading="loading"
        :data="tableTree"
        :default-sort="{prop: search.prop, order: search.order}"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @sort-change="sortChange"
        @selection-change="checkSelected"
        @select-all="checkAll">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="title" label="名称" sortable="custom"></el-table-column>
        <el-table-column prop="icon" label="图标">
            <template slot-scope="scope">
                <i :class="scope.row.icon"></i>
                {{scope.row.icon}}
            </template>
        </el-table-column>
        <el-table-column prop="path" label="访问路径" sortable="custom"></el-table-column>
        <el-table-column prop="sort" label="排序" sortable="custom"></el-table-column>
        <el-table-column prop="status" label="状态" width="100px" sortable="custom">
            <template slot-scope="scope">
                <el-switch
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    :disabled="editAuthority === false"
                    @change="fieldEdit(scope.row, 'status')">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column prop="ifshow" label="菜单" width="100px" sortable="custom">
            <template slot-scope="scope">
                <el-button
                    size="mini"
                    :type="scope.row.ifshow === 1 ? 'success' : 'danger'"
                    :disabled="editAuthority === false"
                    @click="show(scope.row)">
                    {{scope.row.ifshow === 1 ? '显示' : '隐藏'}}
                </el-button>
            </template>
        </el-table-column>
        <el-table-column prop="logwriting" label="日志" width="100px" sortable="custom">
            <template slot-scope="scope">
                <el-switch
                    v-model="scope.row.logwriting"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    :disabled="editAuthority === false"
                    @change="fieldEdit(scope.row, 'logwriting')">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
            <template slot-scope="scope">
                <mk-table-public
                    :edit-url="editUrl"
                    :del-url="delUrl"
                    :push-url="addUrl"
                    :copy-url="addUrl"
                    @edit="openDrawer(scope.row)"
                    @del="del(scope.row)"
                    @push="parentAppend(scope.row)"
                    @copy="copy(scope.row)">
                </mk-table-public>
            </template>
        </el-table-column>
    </el-table>
</div>
{include file="admin_menu/drawer" /}
{include file="$component" /}
<script>
    new Vue({
        el: '#app',
        data() {
            var validateRepeatPath = (rule, value, callback) => {
                if (typeof this.drawerData.id === 'undefined') {
                    let isExist = common.arrayIndex(this.table, value, 'path');
                    if(isExist !== -1) {
                        callback(new Error('列表中路径已存在！'));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            }
            return {
                rows: [],
                table: [],
                tableTree: [],
                tableTreeString: [],
                search:{
                    keyword: "",
                    prop: "sort", 
                    order: "descending",
                },
                url: "adminMenu/index",
                addUrl: "adminMenu/save",
                delUrl: "adminMenu/delete",
                editUrl: "adminMenu/update",
                loading: false,
                select: false,
                drawer: false,
                drawerData: {},
                drawerForm: {
                    pid: "",
                    title: "",
                    icon: "",
                    path: "",
                    sort: 0,
                    status: 1,
                    ifshow: 0,
                    logwriting: 1,
                    isList: 0,
                },
                drawerRules: {
                    pid: [
                        { required: true, message: '请选择父级菜单', trigger: 'blur' },
                    ],
                    title: [
                        { required: true, message: '请输入菜单名称', trigger: 'blur' },
                        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
                    ],
                    path: [
                        { required: true, message: '请输入菜单访问路径', trigger: 'blur' },
                        { min: 2, max: 255, message: '长度在 2 到 255 个字符', trigger: 'blur' },
                        { validator: validateRepeatPath, trigger: 'blur' }
                    ],
                    sort: [
                        { required: true, message: '请输入菜单排序', trigger: 'blur' },
                        { type: 'number', message: '只允许纯数字', trigger: 'blur' },
                    ],
                },
                drawerLoading: false,
            }
        },
        created () {
            this.getData();
        },
        computed: {
            editAuthority() {
                return authorityPath.indexOf(this.editUrl) !== -1;
            },
        },
        methods: {
            /**
             * 获取数据
             */
            getData() {
                let self     = this;
                self.loading = true;
                request.post(self.url, self.search, function(res) {
                    self.loading   = false;
                    self.table     = res.data;
                    self.tableTree = tree.convert(self.table);
                    parent.parentVm.menus = tree.convert(res.publicMenu);
                });
            },
            sortChange(v) {
                this.search = Object.assign({}, this.search, {prop: v.prop , order: v.order});
            },
            /**
             * 向父类追加行
             * @param  {Object} row 当前行
             */
            parentAppend(row) {
                let arr = JSON.parse(JSON.stringify(this.drawerForm));
                arr.pid = row.id;
                this.openDrawer(arr);
            },
            /**
             * 复制
             * @param  {Object} row 当前行
             */
            copy(row) {
                let arr = JSON.parse(JSON.stringify(row));
                delete(arr['id']);
                this.openDrawer(arr);
            },
            /**
             * 打开抽屉
             * @param  {Object} row 当前行
             */
            openDrawer(row = "") {
                let self = this;
                let parentList = []; //不包含本身及下属
                self.drawerData = row === "" ? JSON.parse(JSON.stringify(self.drawerForm)) : JSON.parse(JSON.stringify(row));
                self.table.forEach(function (item, index) {
                    // 下级不显示
                    if (item.id !== self.drawerData.id) {
                        parentList.push(item);
                    }
                });
                self.tableTreeString = tree.convertString(parentList);
                self.tableTreeString.unshift({id: 0, title: "顶级菜单"});
                self.drawer = true;
            },
            /**
             * 保存内容
             */
            saveDrawer() {
                let self = this;
                self.$refs.drawerData.validate((valid) => {
                    if (valid) {
                        let requestUrl = typeof self.drawerData.id === 'undefined' ? self.addUrl : self.editUrl;
                        self.drawerLoading = true;
                        request.post(requestUrl, self.drawerData, function(res){
                            self.drawerLoading = false;
                            if (res.status === 'success') {
                                self.getData();
                                self.drawer = false;
                            } else {
                                self.$message({ showClose: true, message: res.message, type: res.status});
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },
            /**
             * 行删除、批量删除
             * @param  {Object} row 当前行
             */
            del(row = "") {
                let self = this;
                let ids  = row === "" ? common.arrayColumn(self.rows,'id') : [row.id]; 
                self.$confirm('确定删除吗？', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    request.post(self.delUrl, {'ids': ids}, function(res){
                        if(res.status === 'success') {
                            self.getData();
                        } else {
                            self.$message({ showClose: true, message: res.message, type: res.status});
                        }
                    });
                }).catch(() => {});
            },
            /**
             * 单字段修改
             * @param  {Object} row 当前行
             */
            show(row) {
                row.ifshow = row.ifshow === 1 ? 0 : 1;
                this.fieldEdit(row, 'ifshow');
            },
            fieldEdit(row, field) {
                let self = this;
                request.post(self.editUrl, {id: row.id, value: row[field], field: field}, function(res) {
                    if (res.status != 'success') {
                        self.$message({ showClose: true, message: res.message, type: res.status});
                    }
                    self.getData();
                });
            },
            /**
             * 关键词搜索
             * @param  {Object} value 搜索内容
             */
            searchData(value) {
                this.search = Object.assign({}, this.search, {keyword: value.keyword});
            },
            /**
             * 选中行
             * @param  {Object} rows 多行数
             */
            checkSelected(rows) {
                this.rows = rows;
            },
            /**
             * 选中所有行，只有树形结构才需要这样处理
             */
            checkAll() {
                let self    = this;
                let table  = self.$refs.table;
                self.select = self.select ? false : true;
                self.table.forEach(function (item, index){
                    table.toggleRowSelection(item, self.select);
                });
            },
            /**
             * 折叠/展开所有行，只有树形结构才需要这样处理
             */
            expandAll(bool){
                let self    = this;
                let $table  = self.$refs.table;
                self.table.forEach(function (item, index){
                    $table.toggleRowExpansion(item, bool);
                });
            },
        },
        watch: {
            drawer(v) {
                this.$nextTick(()=>{
                    if(! v){
                        // 重置表单
                        this.$refs.drawerData.resetFields();
                    }
                })
            },
            search() {
                this.getData();
            }
        }
    })
</script>
{include file="$footer" /}